#  -*- coding:utf-8 -*- 
"""
@ author: 罗金盛
@ time: 2024/6/12 
@ file: sinong_login.py

"""
import time
import re
import logging
from DrissionPage import WebPage
from DrissionPage.common import Actions
from src.config import Config, LoggerConfig

# 配置日志记录
LoggerConfig.configure_logger('log/sn-audit-report.log')

class SinongLogin:
    def __init__(self):
        """初始化 SinongLogin 类"""
        self.config = Config()  # 加载配置
        self.page = WebPage('d')  # 启动浏览器
        self.ac = Actions(self.page)  # 初始化浏览器操作
        self.logger = logging.getLogger('SinongLogin')  # 获取日志记录器

    def login(self, url):
        """
        尝试登录并处理可能的异常
        :param url (str): 登录页面的URL
        :return: 登录是否成功
        """
        try:
            self.page.get(url)  # 打开登录页面
            user = self.config.sinong_config()['user']  # 获取用户名
            password = self.config.sinong_config()['password']  # 获取密码

            # 输入用户名和密码并点击登录
            self.page('#UserName').input(user)
            self.page('#Password').input(password)
            self.page('@text()=登录').click(by_js=True)
            self.logger.info('登录成功...')
            self.page.wait(2)
            return True
        except Exception as e:
            # 处理异常情况，例如页面上没有登录表单
            self.logger.info(f'不需要进行此步骤！直接开始登录: {e}')
            return True

    def get_url(self):
        """
        获取下一步需要访问的URL
        :return:获取到的URL，如果失败则返回None
        """
        try:
            # 通过XPath查找URL元素
            url_element = self.page('xpath://*[@id="app"]/div/div[1]/div/div[2]/div[2]/div/div/div[2]/a/@href')
            # 使用正则表达式提取URL
            url = re.findall(r"href='(.*?)'", str(url_element))
            if url:
                self.logger.info(f'获取 URL 成功: {url[0]}')
                return url[0]
            else:
                self.logger.error('未找到 URL')
                return None
        except Exception as e:
            self.logger.error(f'获取 URL 失败: {e}')
            return None

    def get_cookies(self):
        """
        获取当前页面的Cookies
        :return:包含Cookies的字典，如果失败则返回None
        """
        try:
            # 获取Cookies并转换为字典格式
            data = self.page.cookies(as_dict=False)
            cookies = {item['name']: item['value'] for item in data}
            time_ = str(int(time.time() * 1000))
            cookies['logintime'] = time_
            self.logger.info('获取 Cookies 成功')
            return cookies
        except Exception as e:
            self.logger.error(f'获取 Cookies 失败: {e}')
            return None

    def run(self):
        """
        运行登录流程并获取Cookies
        :return:登录后的Cookies，如果失败则返回None
        """
        if self.login('https://i-dev.sinongcpa.cn/#/index'):
            url = self.get_url()
            if url:
                self.page.get(url)
                self.page.wait(2)
                cookies = self.get_cookies()
                if cookies:
                    return cookies
            return None

if __name__ == '__main__':
    # 创建 SinongLogin 实例并运行登录过程
    sinong_login = SinongLogin()
    cookies = sinong_login.run()
    if cookies:
        print(cookies)
